<template>
  <div>
    <a-button type="primary" @click="showModal = true">上传图片</a-button>

    <a-modal
      v-if="showModal"
      v-model:open="showModal"
      :closable="false"
      :maskClosable="false"
      ok-text="确认"
      cancel-text="取消"
      @cancel="() => (showModal = false)"
      @ok="handleOk"
    >
      <a-upload-dragger v-bind="uploadProps" @change="handleChange">
        <p class="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p class="ant-upload-text">请将图片拖拽到此处上传</p>
        <p class="ant-upload-hint">
          支持一次上传多个 / 支持 png,jpg,jpeg,gif 格式图片
        </p>
      </a-upload-dragger>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { message } from "ant-design-vue";
import { InboxOutlined } from "@ant-design/icons-vue";
import config from "@/js/config";
import { getToken, checkUrl } from "@/utils";

interface PropsInterface {
  categoryIds: number[];
  onUpdate: () => void;
}

const props = defineProps<PropsInterface>();

const showModal = ref(false);

// 上传配置
const uploadProps = computed(() => ({
  name: "file",
  multiple: true,
  action:
    checkUrl(config.app_url) +
    "backend/v1/upload/minio?category_ids=" +
    props.categoryIds.join(","),
  headers: {
    authorization: "Bearer " + getToken(),
  },
  showUploadList: {
    showRemoveIcon: false,
    showDownloadIcon: false,
  },
}));

// 处理上传
const handleChange = (info: any) => {
  const { status, response } = info.file;
  if (status === "done") {
    if (response.code === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else {
      message.error(response.msg);
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 上传失败`);
  }
};

// 确认
const handleOk = () => {
  props.onUpdate();
  showModal.value = false;
};
</script>
